Your First AI application

Going forward, AI algorithms will be incorporated into more and more everyday applications. For example, you might want to include an image classifier in a smart phone app. To do this, you'd use a deep learning model trained on hundreds of thousands of images as part of the overall application architecture. A large part of software development in the future will be using these types of models as common parts of applications.

In this project, you'll train an image classifier to recognize different species of flowers. You can imagine using something like this in a phone app that tells you the name of the flower your camera is looking at. In practice you'd train this classifier, then export it for use in your application. We'll be using this dataset from Oxford of 102 flower categories, you can see a few examples below.

The project is broken down into multiple steps:

  • Load the image dataset and create a pipeline.
  • Build and Train an image classifier on this dataset.
  • Use your trained model to perform inference on flower images.

We'll lead you through each part which you'll implement in Python.

When you've completed this project, you'll have an application that can be trained on any set of labeled images. Here your network will be learning about flowers and end up as a command line application. But, what you do with your new skills depends on your imagination and effort in building a dataset. For example, imagine an app where you take a picture of a car, it tells you what the make and model is, then looks up information about it. Go build your own dataset and make something new.

Install Datasets and Upgrade TensorFlow

To ensure we can download the latest version of the oxford_flowers102 dataset, let's first install both tensorflow-datasets and tfds-nightly.

  • tensorflow-datasets is the stable version that is released on a cadence of every few months
  • tfds-nightly is released every day and has the latest version of the datasets

We'll also upgrade TensorFlow to ensure we have a version that is compatible with the latest version of the dataset.

In [1]:
%pip --no-cache-dir install tensorflow-datasets --user
%pip --no-cache-dir install tfds-nightly --user
%pip --no-cache-dir install --upgrade tensorflow --user
Requirement already satisfied: tensorflow-datasets in /opt/conda/lib/python3.7/site-packages (1.2.0)
Requirement already satisfied: wrapt in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.11.2)
Requirement already satisfied: absl-py in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.8.1)
Requirement already satisfied: protobuf>=3.6.1 in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (3.11.2)
Requirement already satisfied: dill in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.3.1.1)
Requirement already satisfied: termcolor in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.1.0)
Requirement already satisfied: attrs in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (19.3.0)
Requirement already satisfied: requests>=2.19.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (2.22.0)
Requirement already satisfied: promise in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (2.2.1)
Requirement already satisfied: future in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.18.2)
Requirement already satisfied: psutil in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (5.6.7)
Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.12.0)
Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (4.36.1)
Requirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (1.17.4)
Requirement already satisfied: tensorflow-metadata in /opt/conda/lib/python3.7/site-packages (from tensorflow-datasets) (0.14.0)
Requirement already satisfied: setuptools in /opt/conda/lib/python3.7/site-packages (from protobuf>=3.6.1->tensorflow-datasets) (41.4.0)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (1.24.2)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (3.0.4)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (2.8)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tensorflow-datasets) (2019.11.28)
Requirement already satisfied: googleapis-common-protos in /opt/conda/lib/python3.7/site-packages (from tensorflow-metadata->tensorflow-datasets) (1.6.0)
Note: you may need to restart the kernel to use updated packages.
Collecting tfds-nightly
  Downloading https://files.pythonhosted.org/packages/5a/25/08678db9148783e15c8ed2bad63fe6d12f204cd600d50b965d663eea7b99/tfds_nightly-4.6.0.dev202208040045-py3-none-any.whl (4.5MB)
     |████████████████████████████████| 4.5MB 4.5MB/s eta 0:00:01     |█████▊                          | 798kB 4.5MB/s eta 0:00:01     |████████████████▋               | 2.3MB 4.5MB/s eta 0:00:01
Collecting toml
  Downloading https://files.pythonhosted.org/packages/44/6f/7120676b6d73228c96e17f1f794d8ab046fc910d781c8d151120c3f1569e/toml-0.10.2-py2.py3-none-any.whl
Requirement already satisfied: tensorflow-metadata in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.14.0)
Requirement already satisfied: requests>=2.19.0 in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.22.0)
Collecting protobuf>=3.12.2
  Downloading https://files.pythonhosted.org/packages/c6/be/c553117f399613062c7ff4b370386d637df80b404fac7c4231497cdf83cc/protobuf-4.21.4-cp37-abi3-manylinux2014_x86_64.whl (408kB)
     |████████████████████████████████| 409kB 12.2MB/s eta 0:00:01
Collecting importlib-resources; python_version < "3.9"
  Downloading https://files.pythonhosted.org/packages/d3/91/4df247dd4da18b72b5bbabe1fa2b85029c34e1d6f0afdd6329d15d6bf2b5/importlib_resources-5.9.0-py3-none-any.whl
Requirement already satisfied: absl-py in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.8.1)
Requirement already satisfied: tqdm in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (4.36.1)
Collecting etils[epath]
  Downloading https://files.pythonhosted.org/packages/6b/f0/d717858522d20a4493ea93368a6a737ac7db791e199b07524a41982053f7/etils-0.6.0-py3-none-any.whl (98kB)
     |████████████████████████████████| 102kB 13.9MB/s ta 0:00:01
Collecting typing-extensions; python_version < "3.8"
  Downloading https://files.pythonhosted.org/packages/ed/d6/2afc375a8d55b8be879d6b4986d4f69f01115e795e36827fd3a40166028b/typing_extensions-4.3.0-py3-none-any.whl
Requirement already satisfied: numpy in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.17.4)
Requirement already satisfied: promise in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (2.2.1)
Requirement already satisfied: six in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.12.0)
Requirement already satisfied: termcolor in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (1.1.0)
Requirement already satisfied: dill in /opt/conda/lib/python3.7/site-packages (from tfds-nightly) (0.3.1.1)
Requirement already satisfied: googleapis-common-protos in /opt/conda/lib/python3.7/site-packages (from tensorflow-metadata->tfds-nightly) (1.6.0)
Requirement already satisfied: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2.8)
Requirement already satisfied: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (2019.11.28)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (1.24.2)
Requirement already satisfied: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests>=2.19.0->tfds-nightly) (3.0.4)
Collecting zipp>=3.1.0; python_version < "3.10"
  Downloading https://files.pythonhosted.org/packages/f0/36/639d6742bcc3ffdce8b85c31d79fcfae7bb04b95f0e5c4c6f8b206a038cc/zipp-3.8.1-py3-none-any.whl
ERROR: tensorflow-metadata 0.14.0 has requirement protobuf<4,>=3.7, but you'll have protobuf 4.21.4 which is incompatible.
Installing collected packages: toml, protobuf, zipp, importlib-resources, etils, typing-extensions, tfds-nightly
  WARNING: The script tfds is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed etils-0.6.0 importlib-resources-5.9.0 protobuf-4.21.4 tfds-nightly-4.6.0.dev202208040045 toml-0.10.2 typing-extensions-4.3.0 zipp-3.8.1
Note: you may need to restart the kernel to use updated packages.
Collecting tensorflow
  Downloading https://files.pythonhosted.org/packages/db/27/6754ced3dfcdc0507c24df31b5daa9acfa6357f083b355081781fa040404/tensorflow-2.9.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (511.7MB)
     |███████████████▋                | 249.1MB 14.3MB/s eta 0:00:19  |                                | 757kB 4.5MB/s eta 0:01:53     |▍                               | 5.9MB 4.5MB/s eta 0:01:52     |▉                               | 13.6MB 4.5MB/s eta 0:01:50     |█                               | 14.4MB 4.5MB/s eta 0:01:50     |█                               | 16.2MB 16.4MB/s eta 0:00:31     |█▋                              | 26.5MB 16.4MB/s eta 0:00:30     |██                              | 31.6MB 16.4MB/s eta 0:00:30     |██▌                             | 39.1MB 31.0MB/s eta 0:00:16     |██▊                             | 43.2MB 31.0MB/s eta 0:00:16     |██▊                             | 44.0MB 31.0MB/s eta 0:00:16     |███                             | 46.6MB 31.0MB/s eta 0:00:16     |███                             | 47.4MB 12.7MB/s eta 0:00:37     |███                             | 48.2MB 12.7MB/s eta 0:00:37     |███▏                            | 49.8MB 12.7MB/s eta 0:00:37     |███▎                            | 52.1MB 12.7MB/s eta 0:00:37     |███▍                            | 53.8MB 12.7MB/s eta 0:00:37     |███▍                            | 54.6MB 12.7MB/s eta 0:00:36     |████                            | 64.2MB 7.2MB/s eta 0:01:03     |████▏                           | 66.0MB 7.2MB/s eta 0:01:03     |████▎                           | 68.3MB 7.2MB/s eta 0:01:02     |████▎                           | 69.0MB 7.2MB/s eta 0:01:02     |████▍                           | 70.2MB 7.2MB/s eta 0:01:02     |████▌                           | 71.6MB 7.2MB/s eta 0:01:02     |████▌                           | 72.4MB 7.2MB/s eta 0:01:02     |████▌                           | 72.8MB 7.2MB/s eta 0:01:02     |████▋                           | 73.6MB 6.7MB/s eta 0:01:06     |████▋                           | 74.3MB 6.7MB/s eta 0:01:06     |████▊                           | 75.7MB 6.7MB/s eta 0:01:05     |████▉                           | 77.5MB 6.7MB/s eta 0:01:05     |█████                           | 79.5MB 6.7MB/s eta 0:01:05     |█████▏                          | 82.3MB 6.7MB/s eta 0:01:04     |█████▏                          | 82.9MB 6.7MB/s eta 0:01:04     |█████▎                          | 85.0MB 6.7MB/s eta 0:01:04     |█████▍                          | 85.7MB 27.2MB/s eta 0:00:16     |█████▍                          | 86.4MB 27.2MB/s eta 0:00:16     |█████▌                          | 87.9MB 27.2MB/s eta 0:00:16     |█████▌                          | 88.6MB 27.2MB/s eta 0:00:16     |█████▋                          | 89.3MB 27.2MB/s eta 0:00:16     |█████▊                          | 91.8MB 27.2MB/s eta 0:00:16     |█████▉                          | 93.1MB 27.2MB/s eta 0:00:16     |██████                          | 94.2MB 27.2MB/s eta 0:00:16     |██████                          | 94.7MB 27.2MB/s eta 0:00:16     |██████                          | 95.1MB 27.2MB/s eta 0:00:16     |██████                          | 97.3MB 4.4MB/s eta 0:01:34     |██████▏                         | 97.8MB 4.4MB/s eta 0:01:34     |██████▏                         | 98.3MB 4.4MB/s eta 0:01:34     |██████▏                         | 99.0MB 4.4MB/s eta 0:01:33     |██████▎                         | 101.1MB 4.4MB/s eta 0:01:33     |██████▍                         | 101.7MB 4.4MB/s eta 0:01:33     |██████▌                         | 104.2MB 4.4MB/s eta 0:01:32     |██████▋                         | 106.3MB 4.4MB/s eta 0:01:32     |██████▉                         | 109.2MB 5.9MB/s eta 0:01:09     |███████                         | 110.6MB 5.9MB/s eta 0:01:08     |███████▎                        | 117.0MB 5.9MB/s eta 0:01:07     |███████▌                        | 120.4MB 5.9MB/s eta 0:01:07     |███████▋                        | 122.4MB 10.0MB/s eta 0:00:40     |███████▉                        | 125.3MB 10.0MB/s eta 0:00:39     |████████                        | 126.6MB 10.0MB/s eta 0:00:39     |████████                        | 129.4MB 10.0MB/s eta 0:00:39     |████████▏                       | 130.8MB 10.0MB/s eta 0:00:39     |████████▎                       | 131.5MB 10.0MB/s eta 0:00:39     |████████▎                       | 132.9MB 10.0MB/s eta 0:00:39     |████████▍                       | 134.9MB 14.0MB/s eta 0:00:27     |████████▌                       | 135.6MB 14.0MB/s eta 0:00:27     |████████▋                       | 136.9MB 14.0MB/s eta 0:00:27     |████████▋                       | 138.5MB 14.0MB/s eta 0:00:27     |████████▉                       | 140.5MB 14.0MB/s eta 0:00:27     |█████████                       | 144.4MB 14.0MB/s eta 0:00:27     |█████████▏                      | 145.8MB 14.0MB/s eta 0:00:27     |█████████▏                      | 147.1MB 10.3MB/s eta 0:00:36     |█████████▎                      | 148.6MB 10.3MB/s eta 0:00:36     |█████████▍                      | 149.9MB 10.3MB/s eta 0:00:35     |█████████▌                      | 151.3MB 10.3MB/s eta 0:00:35     |█████████▊                      | 154.8MB 10.3MB/s eta 0:00:35     |██████████                      | 158.8MB 15.4MB/s eta 0:00:23     |██████████                      | 159.5MB 15.4MB/s eta 0:00:23     |██████████▎                     | 163.8MB 15.4MB/s eta 0:00:23     |██████████▊                     | 171.4MB 11.9MB/s eta 0:00:29     |██████████▉                     | 173.4MB 11.9MB/s eta 0:00:29     |███████████                     | 174.6MB 11.9MB/s eta 0:00:29     |███████████                     | 176.4MB 11.9MB/s eta 0:00:29     |███████████                     | 177.6MB 11.9MB/s eta 0:00:29     |███████████▏                    | 178.2MB 11.9MB/s eta 0:00:29     |███████████▌                    | 184.2MB 15.6MB/s eta 0:00:22     |███████████▊                    | 187.5MB 15.6MB/s eta 0:00:21     |███████████▉                    | 188.8MB 15.6MB/s eta 0:00:21     |███████████▉                    | 189.5MB 15.6MB/s eta 0:00:21     |████████████                    | 190.9MB 15.6MB/s eta 0:00:21     |████████████                    | 192.2MB 15.6MB/s eta 0:00:21     |████████████▍                   | 199.0MB 11.2MB/s eta 0:00:28     |████████████▌                   | 199.6MB 11.2MB/s eta 0:00:28     |████████████▌                   | 200.3MB 11.2MB/s eta 0:00:28     |████████████▋                   | 201.0MB 11.2MB/s eta 0:00:28     |████████████▋                   | 201.6MB 11.2MB/s eta 0:00:28     |████████████▋                   | 202.3MB 11.2MB/s eta 0:00:28     |████████████▉                   | 205.4MB 11.2MB/s eta 0:00:28     |█████████████▏                  | 210.6MB 11.5MB/s eta 0:00:27     |█████████████▎                  | 213.2MB 11.5MB/s eta 0:00:26     |█████████████▌                  | 216.2MB 11.5MB/s eta 0:00:26     |█████████████▋                  | 216.8MB 11.5MB/s eta 0:00:26     |█████████████▊                  | 219.4MB 11.5MB/s eta 0:00:26     |██████████████                  | 223.2MB 6.0MB/s eta 0:00:49     |██████████████                  | 223.9MB 6.0MB/s eta 0:00:49     |██████████████                  | 224.5MB 6.0MB/s eta 0:00:48     |██████████████                  | 225.2MB 6.0MB/s eta 0:00:48     |██████████████▎                 | 228.3MB 6.0MB/s eta 0:00:48     |██████████████▍                 | 230.2MB 6.0MB/s eta 0:00:47     |██████████████▍                 | 230.8MB 6.0MB/s eta 0:00:47     |██████████████▌                 | 232.1MB 5.0MB/s eta 0:00:57     |██████████████▌                 | 232.7MB 5.0MB/s eta 0:00:57     |██████████████▋                 | 234.0MB 5.0MB/s eta 0:00:57     |██████████████▉                 | 236.7MB 5.0MB/s eta 0:00:56     |███████████████                 | 239.2MB 5.0MB/s eta 0:00:56     |███████████████▏                | 241.8MB 5.0MB/s eta 0:00:55     |███████████████▎                | 244.5MB 14.3MB/s eta 0:00:19     |███████████████▎                | 245.1MB 14.3MB/s eta 0:00:19     |███████████████▍                | 245.7MB 14.3MB/s eta 0:00:19     |███████████████▍                | 246.4MB 14.3MB/s eta 0:00:19     |███████████████▌                | 247.1MB 14.3MB/s eta 0:00:19     |███████████████▌                | 247.8MB 14.3MB/s eta 0:00:19     |███████████████▌                | 248.4MB 14.3MB/s eta 0:00:19     |███████████████████████████████▋| 505.3MB 8.9MB/s eta 0:00:012     |███████████████▉                | 252.7MB 14.3MB/s eta 0:00:19     |███████████████▉                | 253.3MB 14.3MB/s eta 0:00:19     |███████████████▉                | 254.0MB 17.6MB/s eta 0:00:15     |████████████████                | 255.2MB 17.6MB/s eta 0:00:15     |████████████████                | 255.7MB 17.6MB/s eta 0:00:15     |████████████████▎               | 259.7MB 17.6MB/s eta 0:00:15     |████████████████▎               | 260.3MB 17.6MB/s eta 0:00:15     |████████████████▊               | 266.6MB 4.6MB/s eta 0:00:54     |████████████████▊               | 267.9MB 4.6MB/s eta 0:00:53     |█████████████████               | 270.3MB 4.6MB/s eta 0:00:53     |█████████████████               | 270.9MB 4.6MB/s eta 0:00:53     |█████████████████               | 273.1MB 4.6MB/s eta 0:00:52     |█████████████████▏              | 274.5MB 4.6MB/s eta 0:00:52     |█████████████████▎              | 276.6MB 4.1MB/s eta 0:00:57     |█████████████████▍              | 277.7MB 4.1MB/s eta 0:00:57     |█████████████████▋              | 281.5MB 4.1MB/s eta 0:00:56     |█████████████████▊              | 282.9MB 4.1MB/s eta 0:00:56     |█████████████████▊              | 284.2MB 4.1MB/s eta 0:00:56     |█████████████████▉              | 284.9MB 4.1MB/s eta 0:00:55     |██████████████████              | 286.9MB 4.1MB/s eta 0:00:55     |██████████████████              | 288.3MB 4.4MB/s eta 0:00:51     |██████████████████              | 288.9MB 4.4MB/s eta 0:00:51     |██████████████████▎             | 292.9MB 4.4MB/s eta 0:00:50     |██████████████████▊             | 299.0MB 4.4MB/s eta 0:00:49     |██████████████████▉             | 301.2MB 4.4MB/s eta 0:00:48     |███████████████████             | 305.2MB 4.4MB/s eta 0:00:47     |███████████████████▏            | 307.2MB 4.4MB/s eta 0:00:46     |███████████████████▎            | 308.0MB 4.4MB/s eta 0:00:46     |███████████████████▌            | 311.8MB 4.4MB/s eta 0:00:45     |███████████████████▋            | 313.2MB 4.4MB/s eta 0:00:45     |███████████████████▉            | 317.3MB 4.4MB/s eta 0:00:44     |███████████████████▉            | 318.0MB 4.4MB/s eta 0:00:44     |████████████████████            | 320.1MB 4.4MB/s eta 0:00:44     |████████████████████            | 321.5MB 4.4MB/s eta 0:00:43     |████████████████████▎           | 324.3MB 4.4MB/s eta 0:00:43     |████████████████████▎           | 324.9MB 4.4MB/s eta 0:00:43     |████████████████████▍           | 326.3MB 3.7MB/s eta 0:00:51     |████████████████████▋           | 329.0MB 3.7MB/s eta 0:00:50     |████████████████████▋           | 329.7MB 3.7MB/s eta 0:00:50     |████████████████████▋           | 330.4MB 3.7MB/s eta 0:00:50     |████████████████████▊           | 331.0MB 3.7MB/s eta 0:00:50     |████████████████████▊           | 331.7MB 3.7MB/s eta 0:00:50     |████████████████████▉           | 332.3MB 3.7MB/s eta 0:00:50     |█████████████████████           | 336.6MB 3.7MB/s eta 0:00:48     |█████████████████████▎          | 339.4MB 4.3MB/s eta 0:00:40     |█████████████████████▎          | 340.8MB 4.3MB/s eta 0:00:40     |█████████████████████▍          | 341.4MB 4.3MB/s eta 0:00:40     |█████████████████████▊          | 348.1MB 4.3MB/s eta 0:00:38     |██████████████████████          | 353.2MB 4.1MB/s eta 0:00:39     |██████████████████████▏         | 355.1MB 4.1MB/s eta 0:00:39     |██████████████████████▍         | 357.5MB 4.1MB/s eta 0:00:38     |██████████████████████▍         | 358.2MB 4.1MB/s eta 0:00:38     |██████████████████████▋         | 361.1MB 4.5MB/s eta 0:00:34     |██████████████████████▊         | 363.0MB 4.5MB/s eta 0:00:34     |██████████████████████▊         | 363.6MB 4.5MB/s eta 0:00:33     |██████████████████████▉         | 364.8MB 4.5MB/s eta 0:00:33     |██████████████████████▉         | 365.4MB 4.5MB/s eta 0:00:33     |███████████████████████         | 366.7MB 4.5MB/s eta 0:00:33     |███████████████████████         | 367.3MB 4.5MB/s eta 0:00:33     |███████████████████████         | 368.6MB 4.5MB/s eta 0:00:32     |███████████████████████         | 369.3MB 4.5MB/s eta 0:00:32     |███████████████████████▏        | 369.9MB 4.5MB/s eta 0:00:32     |███████████████████████▍        | 374.4MB 4.4MB/s eta 0:00:32     |███████████████████████▋        | 378.0MB 4.4MB/s eta 0:00:31     |███████████████████████▊        | 379.8MB 4.4MB/s eta 0:00:31     |███████████████████████▉        | 380.4MB 4.4MB/s eta 0:00:30     |███████████████████████▉        | 381.1MB 4.4MB/s eta 0:00:30     |████████████████████████        | 382.4MB 13.4MB/s eta 0:00:10     |████████████████████████▏       | 386.8MB 13.4MB/s eta 0:00:10     |████████████████████████▍       | 390.4MB 13.4MB/s eta 0:00:10     |████████████████████████▉       | 396.4MB 14.3MB/s eta 0:00:09     |████████████████████████▉       | 397.1MB 14.3MB/s eta 0:00:09     |█████████████████████████▎      | 404.0MB 14.3MB/s eta 0:00:08     |█████████████████████████▍      | 406.0MB 14.3MB/s eta 0:00:08     |█████████████████████████▌      | 408.1MB 12.4MB/s eta 0:00:09     |█████████████████████████▉      | 413.0MB 12.4MB/s eta 0:00:08     |█████████████████████████▉      | 413.7MB 12.4MB/s eta 0:00:08     |██████████████████████████      | 416.4MB 12.4MB/s eta 0:00:08     |██████████████████████████      | 417.1MB 12.4MB/s eta 0:00:08     |██████████████████████████▏     | 418.4MB 12.4MB/s eta 0:00:08     |██████████████████████████▎     | 421.1MB 13.9MB/s eta 0:00:07     |██████████████████████████▊     | 426.6MB 13.9MB/s eta 0:00:07     |███████████████████████████▎    | 437.0MB 8.7MB/s eta 0:00:09     |███████████████████████████▍    | 438.4MB 8.7MB/s eta 0:00:09     |███████████████████████████▌    | 439.1MB 8.7MB/s eta 0:00:09     |███████████████████████████▌    | 439.8MB 8.7MB/s eta 0:00:09     |███████████████████████████▋    | 441.2MB 8.7MB/s eta 0:00:09     |███████████████████████████▊    | 444.0MB 24.4MB/s eta 0:00:03     |████████████████████████████    | 446.0MB 24.4MB/s eta 0:00:03     |████████████████████████████    | 447.5MB 24.4MB/s eta 0:00:03     |████████████████████████████    | 449.1MB 24.4MB/s eta 0:00:03     |████████████████████████████▏   | 451.1MB 24.4MB/s eta 0:00:03     |████████████████████████████▍   | 453.2MB 24.4MB/s eta 0:00:03     |████████████████████████████▍   | 453.8MB 24.4MB/s eta 0:00:03     |████████████████████████████▌   | 455.1MB 24.4MB/s eta 0:00:03     |████████████████████████████▌   | 456.3MB 43.3MB/s eta 0:00:02     |████████████████████████████▋   | 458.0MB 43.3MB/s eta 0:00:02     |████████████████████████████▊   | 459.6MB 43.3MB/s eta 0:00:02     |█████████████████████████████   | 463.0MB 43.3MB/s eta 0:00:02     |█████████████████████████████▏  | 466.3MB 43.3MB/s eta 0:00:02     |█████████████████████████████▍  | 469.2MB 4.3MB/s eta 0:00:10     |█████████████████████████████▍  | 469.9MB 4.3MB/s eta 0:00:10     |█████████████████████████████▍  | 470.5MB 4.3MB/s eta 0:00:10     |██████████████████████████████  | 478.2MB 4.3MB/s eta 0:00:08     |██████████████████████████████▏ | 482.9MB 5.9MB/s eta 0:00:05     |██████████████████████████████▎ | 484.3MB 5.9MB/s eta 0:00:05     |██████████████████████████████▎ | 485.0MB 5.9MB/s eta 0:00:05     |██████████████████████████████▍ | 486.4MB 5.9MB/s eta 0:00:05     |██████████████████████████████▌ | 487.7MB 5.9MB/s eta 0:00:05     |██████████████████████████████▊ | 491.1MB 5.9MB/s eta 0:00:04     |██████████████████████████████▊ | 491.8MB 4.8MB/s eta 0:00:05     |███████████████████████████████ | 495.9MB 4.8MB/s eta 0:00:04     |███████████████████████████████ | 496.6MB 4.8MB/s eta 0:00:04     |███████████████████████████████ | 497.3MB 4.8MB/s eta 0:00:04     |███████████████████████████████▎| 499.4MB 4.8MB/s eta 0:00:03     |███████████████████████████████▍| 501.4MB 4.8MB/s eta 0:00:031.5MB 4.8MB/s eta 0:00:03�██████████████▍| 501.8MB 4.8MB/s eta 0:00:03███████████████████████████████▍| 502.1MB 4.8MB/s eta 0:00:02��██▍| 502.4MB 4.8MB/s eta 0:00:02B 8.9MB/s eta 0:00:01█████████████▌| 504.4MB 8.9MB/s eta 0:00:01��█████████████████████████████▋| 504.7MB 8.9MB/s eta 0:00:01�█▋| 505.0MB 8.9MB/s eta 0:00:01     |████████████████████████████████| 511.7MB 5.3MB/s eta 0:00:01B 8.9MB/s eta 0:00:01█████████████▊| 506.9MB 8.9MB/s eta 0:00:01��█████████████████████████████▊| 507.2MB 8.9MB/s eta 0:00:01�█▊| 507.5MB 8.9MB/s eta 0:00:01     |███████████████████████████████▉| 508.9MB 8.9MB/s eta 0:00:019.2MB 8.9MB/s eta 0:00:01�██████████████▉| 509.5MB 8.9MB/s eta 0:00:01███████████████████████████████▉| 509.8MB 8.9MB/s eta 0:00:01��███| 510.1MB 8.9MB/s eta 0:00:01     |████████████████████████████████| 511.6MB 5.3MB/s eta 0:00:01
Collecting flatbuffers<2,>=1.12
  Downloading https://files.pythonhosted.org/packages/eb/26/712e578c5f14e26ae3314c39a1bdc4eb2ec2f4ddc89b708cf8e0a0d20423/flatbuffers-1.12-py2.py3-none-any.whl
Requirement already satisfied, skipping upgrade: gast<=0.4.0,>=0.2.1 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (0.2.2)
Requirement already satisfied, skipping upgrade: setuptools in /opt/conda/lib/python3.7/site-packages (from tensorflow) (41.4.0)
Requirement already satisfied, skipping upgrade: termcolor>=1.1.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.1.0)
Collecting tensorflow-io-gcs-filesystem>=0.23.1
  Downloading https://files.pythonhosted.org/packages/02/e2/e52124db811cac83d1773efd3c1e456db3aedb7974a5a4c431126bc2da79/tensorflow_io_gcs_filesystem-0.26.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (2.4MB)
     |████████████████████████████████| 2.4MB 53.9MB/s eta 0:00:01     |█████████████████████████▎      | 1.9MB 53.9MB/s eta 0:00:01
Collecting absl-py>=1.0.0
  Downloading https://files.pythonhosted.org/packages/a5/b8/fc74a554a6fc7f26744c883ebfe405cf49c1f1320f13ee874aee47c70e1d/absl_py-1.2.0-py3-none-any.whl (123kB)
     |████████████████████████████████| 133kB 53.5MB/s eta 0:00:01
Collecting tensorboard<2.10,>=2.9
  Downloading https://files.pythonhosted.org/packages/ee/0d/23812e6ce63b3d87c39bc9fee83e28c499052fa83fddddd7daea21a6d620/tensorboard-2.9.1-py3-none-any.whl (5.8MB)
     |████████████████████████████████| 5.8MB 19.9MB/s eta 0:00:01     |████████████████████████▌       | 4.4MB 19.9MB/s eta 0:00:01     |█████████████████████████████▎  | 5.3MB 19.9MB/s eta 0:00:01��█████████ | 5.6MB 19.9MB/s eta 0:00:01
Collecting keras-preprocessing>=1.1.1
  Downloading https://files.pythonhosted.org/packages/79/4c/7c3275a01e12ef9368a892926ab932b33bb13d55794881e3573482b378a7/Keras_Preprocessing-1.1.2-py2.py3-none-any.whl (42kB)
     |████████████████████████████████| 51kB 24.2MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: opt-einsum>=2.3.2 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (3.1.0)
Collecting tensorflow-estimator<2.10.0,>=2.9.0rc0
  Downloading https://files.pythonhosted.org/packages/61/e1/a72ec68403d91ba433018db58859fd4706642aa9d0fb44ff778934fc4c2c/tensorflow_estimator-2.9.0-py2.py3-none-any.whl (438kB)
     |████████████████████████████████| 440kB 7.0MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: six>=1.12.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.12.0)
Requirement already satisfied, skipping upgrade: h5py>=2.9.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (2.9.0)
Collecting astunparse>=1.6.0
  Downloading https://files.pythonhosted.org/packages/2b/03/13dde6512ad7b4557eb792fbcf0c653af6076b81e5941d36ec61f7ce6028/astunparse-1.6.3-py2.py3-none-any.whl
Requirement already satisfied, skipping upgrade: google-pasta>=0.1.1 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (0.1.8)
Collecting libclang>=13.0.0
  Downloading https://files.pythonhosted.org/packages/45/ff/2a6a2a536fc9a2893a6abfb8bbe317200db0475a0c474eccc9d47fa09d48/libclang-14.0.6-py2.py3-none-manylinux2010_x86_64.whl (14.1MB)
     |████████████████████████████████| 14.1MB 10.1MB/s eta 0:00:01   |█▎                              | 583kB 7.7MB/s eta 0:00:02                          | 1.1MB 7.7MB/s eta 0:00:02s eta 0:00:02     |█████████████▏                  | 5.8MB 7.7MB/s eta 0:00:02     |█████████████████▉              | 7.8MB 7.7MB/s eta 0:00:01     |███████████████████▏            | 8.4MB 7.7MB/s eta 0:00:01     |██████████████████████▍         | 9.9MB 7.7MB/s eta 0:00:01     |█████████████████████████▉      | 11.4MB 7.7MB/s eta 0:00:01     |██████████████████████████████▌ | 13.4MB 10.1MB/s eta 0:00:01
Collecting grpcio<2.0,>=1.24.3
  Downloading https://files.pythonhosted.org/packages/6e/15/e6f3805d5003b894cce47af918c6419f2b27cec8d48722087005831203b4/grpcio-1.47.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (4.5MB)
     |████████████████████████████████| 4.5MB 19.8MB/s eta 0:00:01
Collecting packaging
  Downloading https://files.pythonhosted.org/packages/05/8e/8de486cbd03baba4deef4142bd643a3e7bbe954a784dc1bb17142572d127/packaging-21.3-py3-none-any.whl (40kB)
     |████████████████████████████████| 40kB 39.0MB/s eta 0:00:01
Collecting numpy>=1.20
  Downloading https://files.pythonhosted.org/packages/6d/ad/ff3b21ebfe79a4d25b4a4f8e5cf9fd44a204adb6b33c09010f566f51027a/numpy-1.21.6-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl (15.7MB)
     |████████████████████████████████| 15.7MB 5.4MB/s eta 0:00:01    |▍                               | 184kB 6.1MB/s eta 0:00:03           | 1.5MB 6.1MB/s eta 0:00:03                       | 2.1MB 6.1MB/s eta 0:00:03     |███████▋                        | 3.7MB 6.1MB/s eta 0:00:02     |█████████▏                      | 4.5MB 6.1MB/s eta 0:00:02     |█████████████▌                  | 6.6MB 6.1MB/s eta 0:00:02     |████████████████▌               | 8.1MB 6.1MB/s eta 0:00:02     |███████████████████████▏        | 11.4MB 6.1MB/s eta 0:00:01     |████████████████████████▋       | 12.1MB 6.1MB/s eta 0:00:01
Collecting keras<2.10.0,>=2.9.0rc0
  Downloading https://files.pythonhosted.org/packages/ff/ff/f25909606aed26981a8bd6d263f89d64a20ca5e5316e6aafb4c75d9ec8ae/keras-2.9.0-py2.py3-none-any.whl (1.6MB)
     |████████████████████████████████| 1.6MB 13.0MB/s eta 0:00:01     |██▋                             | 133kB 13.0MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: wrapt>=1.11.0 in /opt/conda/lib/python3.7/site-packages (from tensorflow) (1.11.2)
Collecting protobuf<3.20,>=3.9.2
  Downloading https://files.pythonhosted.org/packages/03/6b/12b307892ef5e9f4a1a92f5996922561c453540f5ce22a09038d2486b451/protobuf-3.19.4-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (1.1MB)
     |████████████████████████████████| 1.1MB 9.0MB/s eta 0:00:01     |██████████                      | 327kB 9.0MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: typing-extensions>=3.6.6 in /root/.local/lib/python3.7/site-packages (from tensorflow) (4.3.0)
Collecting google-auth-oauthlib<0.5,>=0.4.1
  Downloading https://files.pythonhosted.org/packages/b1/0e/0636cc1448a7abc444fb1b3a63655e294e0d2d49092dc3de05241be6d43c/google_auth_oauthlib-0.4.6-py2.py3-none-any.whl
Collecting tensorboard-data-server<0.7.0,>=0.6.0
  Downloading https://files.pythonhosted.org/packages/60/f9/802efd84988bffd9f644c03b6e66fde8e76c3aa33db4279ddd11c5d61f4b/tensorboard_data_server-0.6.1-py3-none-manylinux2010_x86_64.whl (4.9MB)
     |████████████████████████████████| 4.9MB 54.4MB/s eta 0:00:01     |████▏                           | 645kB 54.4MB/s eta 0:00:01:00:01/s eta 0:00:01
Requirement already satisfied, skipping upgrade: requests<3,>=2.21.0 in /opt/conda/lib/python3.7/site-packages (from tensorboard<2.10,>=2.9->tensorflow) (2.22.0)
Collecting tensorboard-plugin-wit>=1.6.0
  Downloading https://files.pythonhosted.org/packages/e0/68/e8ecfac5dd594b676c23a7f07ea34c197d7d69b3313afdf8ac1b0a9905a2/tensorboard_plugin_wit-1.8.1-py3-none-any.whl (781kB)
     |████████████████████████████████| 788kB 7.7MB/s eta 0:00:01
Collecting werkzeug>=1.0.1
  Downloading https://files.pythonhosted.org/packages/c0/93/d6d60870e47162ea6a1bbdd787649eea776b2a70618dd66ed87cb2238543/Werkzeug-2.2.1-py3-none-any.whl (232kB)
     |████████████████████████████████| 235kB 27.5MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: markdown>=2.6.8 in /opt/conda/lib/python3.7/site-packages (from tensorboard<2.10,>=2.9->tensorflow) (3.1.1)
Requirement already satisfied, skipping upgrade: wheel>=0.26 in /opt/conda/lib/python3.7/site-packages (from tensorboard<2.10,>=2.9->tensorflow) (0.33.6)
Collecting google-auth<3,>=1.6.3
  Downloading https://files.pythonhosted.org/packages/7b/17/0b14f55fc8ff002b92e2deb796dd9e28a65ca1a6272d9d844e99051afb67/google_auth-2.9.1-py2.py3-none-any.whl (167kB)
     |████████████████████████████████| 174kB 14.9MB/s eta 0:00:01
Requirement already satisfied, skipping upgrade: pyparsing!=3.0.5,>=2.0.2 in /opt/conda/lib/python3.7/site-packages (from packaging->tensorflow) (2.4.6)
Collecting requests-oauthlib>=0.7.0
  Downloading https://files.pythonhosted.org/packages/6f/bb/5deac77a9af870143c684ab46a7934038a53eb4aa975bc0687ed6ca2c610/requests_oauthlib-1.3.1-py2.py3-none-any.whl
Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (1.24.2)
Requirement already satisfied, skipping upgrade: idna<2.9,>=2.5 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (2.8)
Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (2019.11.28)
Requirement already satisfied, skipping upgrade: chardet<3.1.0,>=3.0.2 in /opt/conda/lib/python3.7/site-packages (from requests<3,>=2.21.0->tensorboard<2.10,>=2.9->tensorflow) (3.0.4)
Collecting MarkupSafe>=2.1.1
  Downloading https://files.pythonhosted.org/packages/9f/83/b221ce5a0224f409b9f02b0dc6cb0b921c46033f4870d64fa3e8a96af701/MarkupSafe-2.1.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl
Collecting rsa<5,>=3.1.4; python_version >= "3.6"
  Downloading https://files.pythonhosted.org/packages/49/97/fa78e3d2f65c02c8e1268b9aba606569fe97f6c8f7c2d74394553347c145/rsa-4.9-py3-none-any.whl
Collecting pyasn1-modules>=0.2.1
  Downloading https://files.pythonhosted.org/packages/95/de/214830a981892a3e286c3794f41ae67a4495df1108c3da8a9f62159b9a9d/pyasn1_modules-0.2.8-py2.py3-none-any.whl (155kB)
     |████████████████████████████████| 163kB 17.3MB/s eta 0:00:01
Collecting cachetools<6.0,>=2.0.0
  Downloading https://files.pythonhosted.org/packages/68/aa/5fc646cae6e997c3adf3b0a7e257cda75cff21fcba15354dffd67789b7bb/cachetools-5.2.0-py3-none-any.whl
Collecting oauthlib>=3.0.0
  Downloading https://files.pythonhosted.org/packages/1d/46/5ee2475e1b46a26ca0fa10d3c1d479577fde6ee289f8c6aa6d7ec33e31fd/oauthlib-3.2.0-py3-none-any.whl (151kB)
     |████████████████████████████████| 153kB 11.7MB/s eta 0:00:01    |███████████████▏                | 71kB 52.3MB/s eta 0:00:01
Collecting pyasn1>=0.1.3
  Downloading https://files.pythonhosted.org/packages/62/1e/a94a8d635fa3ce4cfc7f506003548d0a2447ae76fd5ca53932970fe3053f/pyasn1-0.4.8-py2.py3-none-any.whl (77kB)
     |████████████████████████████████| 81kB 14.8MB/s eta 0:00:01
Installing collected packages: flatbuffers, tensorflow-io-gcs-filesystem, absl-py, oauthlib, requests-oauthlib, pyasn1, rsa, pyasn1-modules, cachetools, google-auth, google-auth-oauthlib, tensorboard-data-server, tensorboard-plugin-wit, MarkupSafe, werkzeug, numpy, protobuf, grpcio, tensorboard, keras-preprocessing, tensorflow-estimator, astunparse, libclang, packaging, keras, tensorflow
  WARNING: The scripts pyrsa-decrypt, pyrsa-encrypt, pyrsa-keygen, pyrsa-priv2pub, pyrsa-sign and pyrsa-verify are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The script google-oauthlib-tool is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The scripts f2py, f2py3 and f2py3.7 are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  Found existing installation: protobuf 4.21.4
    Uninstalling protobuf-4.21.4:
      Successfully uninstalled protobuf-4.21.4
  WARNING: The script tensorboard is installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The scripts estimator_ckpt_converter, import_pb_to_tensorboard, saved_model_cli, tensorboard, tf_upgrade_v2, tflite_convert, toco and toco_from_protos are installed in '/root/.local/bin' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
Successfully installed MarkupSafe-2.1.1 absl-py-1.2.0 astunparse-1.6.3 cachetools-5.2.0 flatbuffers-1.12 google-auth-2.9.1 google-auth-oauthlib-0.4.6 grpcio-1.47.0 keras-2.9.0 keras-preprocessing-1.1.2 libclang-14.0.6 numpy-1.21.6 oauthlib-3.2.0 packaging-21.3 protobuf-3.19.4 pyasn1-0.4.8 pyasn1-modules-0.2.8 requests-oauthlib-1.3.1 rsa-4.9 tensorboard-2.9.1 tensorboard-data-server-0.6.1 tensorboard-plugin-wit-1.8.1 tensorflow-2.9.1 tensorflow-estimator-2.9.0 tensorflow-io-gcs-filesystem-0.26.0 werkzeug-2.2.1
Note: you may need to restart the kernel to use updated packages.

After the above installations have finished be sure to restart the kernel. You can do this by going to Kernel > Restart.

In [1]:
# Import TensorFlow 
import tensorflow as tf
import tensorflow_datasets as tfds
import tensorflow_hub as hub
tfds.disable_progress_bar()
# Ignore some warnings that are not relevant (you can remove this if you prefer)
import warnings
warnings.filterwarnings('ignore')
In [2]:
# TODO: Make all other necessary imports.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import json
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from workspace_utils import active_session
import logging
logger = tf.get_logger()
logger.setLevel(logging.ERROR)
import time
from PIL import Image
import random
In [3]:
# Some other recommended settings:
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
tfds.disable_progress_bar()

Load the Dataset

Here you'll use tensorflow_datasets to load the Oxford Flowers 102 dataset. This dataset has 3 splits: 'train', 'test', and 'validation'. You'll also need to make sure the training data is normalized and resized to 224x224 pixels as required by the pre-trained networks.

The validation and testing sets are used to measure the model's performance on data it hasn't seen yet, but you'll still need to normalize and resize the images to the appropriate size.

In [4]:
# TODO: Load the dataset with TensorFlow Datasets. Hint: use tfds.load()
# TODO: Create a training set, a validation set and a test set.
splits = ['train', 'validation','test'] #[:60%], [60%:80%], [80%:100%]

(train, val, test), dataset_info = tfds.load('oxford_flowers102', 
                                   split=splits, 
                                   as_supervised=True, 
                                   with_info=True)
Downloading and preparing dataset 328.90 MiB (download: 328.90 MiB, generated: 331.34 MiB, total: 660.25 MiB) to /root/tensorflow_datasets/oxford_flowers102/2.1.1...
Dataset oxford_flowers102 downloaded and prepared to /root/tensorflow_datasets/oxford_flowers102/2.1.1. Subsequent calls will reuse this data.

Explore the Dataset

In [5]:
dataset_info
Out[5]:
tfds.core.DatasetInfo(
    name='oxford_flowers102',
    full_name='oxford_flowers102/2.1.1',
    description="""
    The Oxford Flowers 102 dataset is a consistent of 102 flower categories commonly occurring
    in the United Kingdom. Each class consists of between 40 and 258 images. The images have
    large scale, pose and light variations. In addition, there are categories that have large
    variations within the category and several very similar categories.
    
    The dataset is divided into a training set, a validation set and a test set.
    The training set and validation set each consist of 10 images per class (totalling 1020 images each).
    The test set consists of the remaining 6149 images (minimum 20 per class).
    
    Note: The dataset by default comes with a test size larger than the train
    size. For more info see this [issue](https://github.com/tensorflow/datasets/issues/3022).
    """,
    homepage='https://www.robots.ox.ac.uk/~vgg/data/flowers/102/',
    data_path='/tmp/tmp24b7qwm5tfds',
    file_format=tfrecord,
    download_size=328.90 MiB,
    dataset_size=331.34 MiB,
    features=FeaturesDict({
        'file_name': Text(shape=(), dtype=tf.string),
        'image': Image(shape=(None, None, 3), dtype=tf.uint8),
        'label': ClassLabel(shape=(), dtype=tf.int64, num_classes=102),
    }),
    supervised_keys=('image', 'label'),
    disable_shuffling=False,
    splits={
        'test': <SplitInfo num_examples=6149, num_shards=2>,
        'train': <SplitInfo num_examples=1020, num_shards=1>,
        'validation': <SplitInfo num_examples=1020, num_shards=1>,
    },
    citation="""@InProceedings{Nilsback08,
       author = "Nilsback, M-E. and Zisserman, A.",
       title = "Automated Flower Classification over a Large Number of Classes",
       booktitle = "Proceedings of the Indian Conference on Computer Vision, Graphics and Image Processing",
       year = "2008",
       month = "Dec"
    }""",
)
In [6]:
# TODO: Get the number of examples in each set from the dataset info.
for data_set in ['train', 'validation', 'test']:
    print(f'Number of images in {data_set} dataset: {dataset_info.splits[data_set].num_examples}')
# TODO: Get the number of classes in the dataset from the dataset info.
print(f'\nNumber of classes: {dataset_info.features["label"].num_classes}')
Number of images in train dataset: 1020
Number of images in validation dataset: 1020
Number of images in test dataset: 6149

Number of classes: 102
In [7]:
# TODO: Print the shape and corresponding label of 3 images in the training set.
for image, label in train.take(3):
    print(f'An image with label {label} has a shape of:', image.shape)
An image with label 72 has a shape of: (500, 667, 3)
An image with label 84 has a shape of: (500, 666, 3)
An image with label 70 has a shape of: (670, 500, 3)
In [8]:
# TODO: Plot 1 image from the training set. 
# Set the title of the plot to the corresponding image label. 

for image, label in train.take(1):
    image = image.numpy().squeeze()
    label = label.numpy()
plt.imshow(image)
plt.title(f'This image has the label: {label}')
plt.show()

Label Mapping

You'll also need to load in a mapping from label to category name. You can find this in the file label_map.json. It's a JSON object which you can read in with the json module. This will give you a dictionary mapping the integer coded labels to the actual names of the flowers.

In [9]:
with open('label_map.json', 'r') as f:
    class_names = json.load(f)
    
list(class_names.values())[:5]
Out[9]:
['fire lily',
 'canterbury bells',
 'bolero deep blue',
 'pink primrose',
 'mexican aster']
In [10]:
# TODO: Plot 1 image from the training set. Set the title 
# of the plot to the corresponding class name. 
for image, label in train.take(1):
    image = image.numpy().squeeze()
    label = label.numpy()
plt.imshow(image)
plt.title(f'This image has the class: {class_names[str(label)]}')
plt.show()

Create Pipeline

In [16]:
# TODO: Create a pipeline for each set.
batch_size = 64
size  = 224

def normalize(image, label):
    image = tf.cast(image, tf.float32)
    image = tf.image.resize(image, (size, size))
    image /= 255
    return image, label


num_training_examples = dataset_info.splits['train'].num_examples

training_batches = train.cache().shuffle(num_training_examples//4).map(normalize).batch(batch_size).prefetch(1)
validation_batches = val.cache().map(normalize).batch(batch_size).prefetch(1)
testing_batches = test.cache().map(normalize).batch(batch_size).prefetch(1)
WARNING: AutoGraph could not transform <function normalize at 0x7f7a75ecab90> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert

Build and Train the Classifier

Now that the data is ready, it's time to build and train the classifier. You should use the MobileNet pre-trained model from TensorFlow Hub to get the image features. Build and train a new feed-forward classifier using those features.

We're going to leave this part up to you. If you want to talk through it with someone, chat with your fellow students!

Refer to the rubric for guidance on successfully completing this section. Things you'll need to do:

  • Load the MobileNet pre-trained network from TensorFlow Hub.
  • Define a new, untrained feed-forward network as a classifier.
  • Train the classifier.
  • Plot the loss and accuracy values achieved during training for the training and validation set.
  • Save your trained model as a Keras model.

We've left a cell open for you below, but use as many as you need. Our advice is to break the problem up into smaller parts you can run separately. Check that each part is doing what you expect, then move on to the next. You'll likely find that as you work through each part, you'll need to go back and modify your previous code. This is totally normal!

When training make sure you're updating only the weights of the feed-forward network. You should be able to get the validation accuracy above 70% if you build everything right.

Note for Workspace users: One important tip if you're using the workspace to run your code: To avoid having your workspace disconnect during the long-running tasks in this notebook, please read in the earlier page in this lesson called Intro to GPU Workspaces about Keeping Your Session Active. You'll want to include code from the workspace_utils.py module. Also, If your model is over 1 GB when saved as a checkpoint, there might be issues with saving backups in your workspace. If your saved checkpoint is larger than 1 GB (you can open a terminal and check with ls -lh), you should reduce the size of your hidden layers and train again.

In [12]:
# TODO: Build and train your network.
URL = "https://tfhub.dev/google/tf2-preview/mobilenet_v2/feature_vector/4"
feature_extractor = hub.KerasLayer(URL, input_shape=(size, size,3))
feature_extractor.trainable = False
In [13]:
model = tf.keras.Sequential([
        feature_extractor,
        tf.keras.layers.Dense(256, activation="relu"),
        tf.keras.layers.Dense(102, activation = 'softmax')
])

model.summary()
WARNING: AutoGraph could not transform <bound method KerasLayer.call of <tensorflow_hub.keras_layer.KerasLayer object at 0x7fd15c195c90>> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: module 'gast' has no attribute 'Constant'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 keras_layer (KerasLayer)    (None, 1280)              2257984   
                                                                 
 dense (Dense)               (None, 256)               327936    
                                                                 
 dense_1 (Dense)             (None, 102)               26214     
                                                                 
=================================================================
Total params: 2,612,134
Trainable params: 354,150
Non-trainable params: 2,257,984
_________________________________________________________________
In [14]:
with active_session():
    model.compile(optimizer='adam',
                  loss='sparse_categorical_crossentropy',
                  metrics=['accuracy'])

    EPOCHS = 30

    early_stopping = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=2)

    history = model.fit(training_batches,
                        epochs=EPOCHS,
                        validation_data=validation_batches,
                        callbacks=[early_stopping])
Epoch 1/30
WARNING: AutoGraph could not transform <function Model.make_train_function.<locals>.train_function at 0x7fd1612f7cb0> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
16/16 [==============================] - ETA: 0s - loss: 4.3370 - accuracy: 0.0990WARNING: AutoGraph could not transform <function Model.make_test_function.<locals>.test_function at 0x7fd140ea9b00> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
16/16 [==============================] - 48s 3s/step - loss: 4.3370 - accuracy: 0.0990 - val_loss: 3.5768 - val_accuracy: 0.3020
Epoch 2/30
16/16 [==============================] - 40s 3s/step - loss: 2.5740 - accuracy: 0.5765 - val_loss: 2.2204 - val_accuracy: 0.5765
Epoch 3/30
16/16 [==============================] - 40s 3s/step - loss: 1.2639 - accuracy: 0.8127 - val_loss: 1.5221 - val_accuracy: 0.6892
Epoch 4/30
16/16 [==============================] - 40s 3s/step - loss: 0.6451 - accuracy: 0.9255 - val_loss: 1.2191 - val_accuracy: 0.7392
Epoch 5/30
16/16 [==============================] - 40s 3s/step - loss: 0.3549 - accuracy: 0.9657 - val_loss: 1.0464 - val_accuracy: 0.7569
Epoch 6/30
16/16 [==============================] - 41s 3s/step - loss: 0.2182 - accuracy: 0.9912 - val_loss: 0.9776 - val_accuracy: 0.7745
Epoch 7/30
16/16 [==============================] - 40s 3s/step - loss: 0.1349 - accuracy: 0.9971 - val_loss: 0.9040 - val_accuracy: 0.7843
Epoch 8/30
16/16 [==============================] - 40s 3s/step - loss: 0.0966 - accuracy: 1.0000 - val_loss: 0.8731 - val_accuracy: 0.7833
Epoch 9/30
16/16 [==============================] - 40s 3s/step - loss: 0.0709 - accuracy: 1.0000 - val_loss: 0.8410 - val_accuracy: 0.7922
Epoch 10/30
16/16 [==============================] - 40s 3s/step - loss: 0.0543 - accuracy: 1.0000 - val_loss: 0.8244 - val_accuracy: 0.7941
Epoch 11/30
16/16 [==============================] - 40s 3s/step - loss: 0.0443 - accuracy: 1.0000 - val_loss: 0.8069 - val_accuracy: 0.7990
Epoch 12/30
16/16 [==============================] - 41s 3s/step - loss: 0.0366 - accuracy: 1.0000 - val_loss: 0.7945 - val_accuracy: 0.8000
Epoch 13/30
16/16 [==============================] - 40s 3s/step - loss: 0.0314 - accuracy: 1.0000 - val_loss: 0.7874 - val_accuracy: 0.7951
Epoch 14/30
16/16 [==============================] - 40s 3s/step - loss: 0.0271 - accuracy: 1.0000 - val_loss: 0.7764 - val_accuracy: 0.8029
Epoch 15/30
16/16 [==============================] - 40s 3s/step - loss: 0.0239 - accuracy: 1.0000 - val_loss: 0.7717 - val_accuracy: 0.8020
Epoch 16/30
16/16 [==============================] - 40s 3s/step - loss: 0.0211 - accuracy: 1.0000 - val_loss: 0.7649 - val_accuracy: 0.8049
Epoch 17/30
16/16 [==============================] - 41s 3s/step - loss: 0.0188 - accuracy: 1.0000 - val_loss: 0.7589 - val_accuracy: 0.8000
Epoch 18/30
16/16 [==============================] - 40s 3s/step - loss: 0.0167 - accuracy: 1.0000 - val_loss: 0.7538 - val_accuracy: 0.8049
Epoch 19/30
16/16 [==============================] - 40s 3s/step - loss: 0.0151 - accuracy: 1.0000 - val_loss: 0.7485 - val_accuracy: 0.8069
Epoch 20/30
16/16 [==============================] - 40s 3s/step - loss: 0.0138 - accuracy: 1.0000 - val_loss: 0.7459 - val_accuracy: 0.8029
Epoch 21/30
16/16 [==============================] - 40s 3s/step - loss: 0.0124 - accuracy: 1.0000 - val_loss: 0.7417 - val_accuracy: 0.8059
Epoch 22/30
16/16 [==============================] - 41s 3s/step - loss: 0.0115 - accuracy: 1.0000 - val_loss: 0.7375 - val_accuracy: 0.8069
Epoch 23/30
16/16 [==============================] - 40s 3s/step - loss: 0.0106 - accuracy: 1.0000 - val_loss: 0.7370 - val_accuracy: 0.8039
Epoch 24/30
16/16 [==============================] - 41s 3s/step - loss: 0.0097 - accuracy: 1.0000 - val_loss: 0.7343 - val_accuracy: 0.8049
Epoch 25/30
16/16 [==============================] - 40s 3s/step - loss: 0.0090 - accuracy: 1.0000 - val_loss: 0.7297 - val_accuracy: 0.8069
Epoch 26/30
16/16 [==============================] - 40s 3s/step - loss: 0.0084 - accuracy: 1.0000 - val_loss: 0.7294 - val_accuracy: 0.8078
Epoch 27/30
16/16 [==============================] - 41s 3s/step - loss: 0.0078 - accuracy: 1.0000 - val_loss: 0.7273 - val_accuracy: 0.8059
Epoch 28/30
16/16 [==============================] - 41s 3s/step - loss: 0.0073 - accuracy: 1.0000 - val_loss: 0.7256 - val_accuracy: 0.8078
Epoch 29/30
16/16 [==============================] - 41s 3s/step - loss: 0.0068 - accuracy: 1.0000 - val_loss: 0.7248 - val_accuracy: 0.8098
Epoch 30/30
16/16 [==============================] - 40s 3s/step - loss: 0.0064 - accuracy: 1.0000 - val_loss: 0.7237 - val_accuracy: 0.8078
In [15]:
history.history
Out[15]:
{'loss': [4.336960315704346,
  2.57403564453125,
  1.2639062404632568,
  0.6451235413551331,
  0.35494711995124817,
  0.21818985044956207,
  0.13493964076042175,
  0.09657405316829681,
  0.07090195268392563,
  0.05432428792119026,
  0.0443110391497612,
  0.03655349463224411,
  0.03138404339551926,
  0.027117658406496048,
  0.023871859535574913,
  0.02106555737555027,
  0.018767107278108597,
  0.01669429801404476,
  0.015137659385800362,
  0.013800201006233692,
  0.012435300275683403,
  0.011518108658492565,
  0.010569277219474316,
  0.009700369089841843,
  0.00901009514927864,
  0.008363230153918266,
  0.007795913144946098,
  0.007256726734340191,
  0.006808098405599594,
  0.00635576294735074],
 'accuracy': [0.0990196093916893,
  0.5764706134796143,
  0.8127450942993164,
  0.9254902005195618,
  0.9656862616539001,
  0.9911764860153198,
  0.9970588088035583,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0,
  1.0],
 'val_loss': [3.5768232345581055,
  2.2204368114471436,
  1.5221105813980103,
  1.2191238403320312,
  1.0464109182357788,
  0.977579653263092,
  0.9039831161499023,
  0.8731359839439392,
  0.840953528881073,
  0.8244433403015137,
  0.8068825602531433,
  0.7944885492324829,
  0.7874154448509216,
  0.7764390110969543,
  0.7716692686080933,
  0.7649077773094177,
  0.7588778734207153,
  0.7538292407989502,
  0.7485319375991821,
  0.7458905577659607,
  0.7416921854019165,
  0.7375014424324036,
  0.7370462417602539,
  0.7342716455459595,
  0.7296642661094666,
  0.7293616533279419,
  0.7273179888725281,
  0.7256083488464355,
  0.7248441576957703,
  0.7237229347229004],
 'val_accuracy': [0.3019607961177826,
  0.5764706134796143,
  0.6892156600952148,
  0.7392156720161438,
  0.7568627595901489,
  0.7745097875595093,
  0.7843137383460999,
  0.7833333611488342,
  0.7921568751335144,
  0.7941176295280457,
  0.7990196347236633,
  0.800000011920929,
  0.795098066329956,
  0.8029412031173706,
  0.8019607663154602,
  0.8049019575119019,
  0.800000011920929,
  0.8049019575119019,
  0.8068627715110779,
  0.8029412031173706,
  0.8058823347091675,
  0.8068627715110779,
  0.8039215803146362,
  0.8049019575119019,
  0.8068627715110779,
  0.8078431487083435,
  0.8058823347091675,
  0.8078431487083435,
  0.8098039031028748,
  0.8078431487083435]}
In [16]:
# TODO: Plot the loss and accuracy values achieved during training for the training and validation set.

training_accuracy = history.history['accuracy']
validation_accuracy = history.history['val_accuracy']

training_loss = history.history['loss']
validation_loss = history.history['val_loss']

epochs_range=range(EPOCHS)

plt.figure(figsize=(16, 8))
plt.subplot(1, 2, 1)
plt.plot(epochs_range, training_accuracy, label='Training Accuracy')
plt.plot(epochs_range, validation_accuracy, label='Validation Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')

plt.subplot(1, 2, 2)
plt.plot(epochs_range, training_loss, label='Training Loss')
plt.plot(epochs_range, validation_loss, label='Validation Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss');
In [19]:
for image_batch, label_batch in testing_batches.take(1):
    ps = model.predict(image_batch)
    images = image_batch.numpy().squeeze()
    labels = label_batch.numpy()
    
plt.figure(figsize=(10,15))

for n in range(30):
    plt.subplot(6,5,n+1)
    plt.imshow(images[n], cmap = plt.cm.binary)
    color = 'green' if np.argmax(ps[n]) == labels[n] else 'red'
    plt.title(class_names[str(labels[n])], color = color)
    plt.axis('off')
WARNING: AutoGraph could not transform <function Model.make_predict_function.<locals>.predict_function at 0x7fd142e9ab90> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: 'arguments' object has no attribute 'posonlyargs'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
2/2 [==============================] - 2s 552ms/step

Testing your Network

It's good practice to test your trained network on test data, images the network has never seen either in training or validation. This will give you a good estimate for the model's performance on completely new images. You should be able to reach around 70% accuracy on the test set if the model has been trained well.

In [17]:
# TODO: Print the loss and accuracy values achieved on the entire test set.
loss, accuracy = model.evaluate(testing_batches)

print('\nLoss on the TEST Set: {:,.3f}'.format(loss))
print('Accuracy on the TEST Set: {:.3%}'.format(accuracy))
97/97 [==============================] - 130s 1s/step - loss: 0.8696 - accuracy: 0.7746

Loss on the TEST Set: 0.870
Accuracy on the TEST Set: 77.460%

Save the Model

Now that your network is trained, save the model so you can load it later for making inference. In the cell below save your model as a Keras model (i.e. save it as an HDF5 file).

In [18]:
# TODO: Save your trained model as a Keras model.
t = time.time()
model_path = f'./my_image_clasifier_{t}.h5'
model.save(model_path)

Load the Keras Model

Load the Keras model you saved above.

In [11]:
# TODO: Load the Keras model
model_path_root = './my_image_clasifier.h5'
reloaded_keras_model = tf.keras.models.load_model(model_path_root,
                                    custom_objects={'KerasLayer':hub.KerasLayer}
                                     )
reloaded_keras_model.summary()
WARNING: AutoGraph could not transform <bound method KerasLayer.call of <tensorflow_hub.keras_layer.KerasLayer object at 0x7f1ea43dfd90>> and will run it as-is.
Please report this to the TensorFlow team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output.
Cause: module 'gast' has no attribute 'Constant'
To silence this warning, decorate the function with @tf.autograph.experimental.do_not_convert
Model: "sequential"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 keras_layer (KerasLayer)    (None, 1280)              2257984   
                                                                 
 dense (Dense)               (None, 256)               327936    
                                                                 
 dense_1 (Dense)             (None, 102)               26214     
                                                                 
=================================================================
Total params: 2,612,134
Trainable params: 354,150
Non-trainable params: 2,257,984
_________________________________________________________________

Inference for Classification

Now you'll write a function that uses your trained network for inference. Write a function called predict that takes an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

The predict function will also need to handle pre-processing the input image such that it can be used by your model. We recommend you write a separate function called process_image that performs the pre-processing. You can then call the process_image function from the predict function.

Image Pre-processing

The process_image function should take in an image (in the form of a NumPy array) and return an image in the form of a NumPy array with shape (224, 224, 3).

First, you should convert your image into a TensorFlow Tensor and then resize it to the appropriate size using tf.image.resize.

Second, the pixel values of the input images are typically encoded as integers in the range 0-255, but the model expects the pixel values to be floats in the range 0-1. Therefore, you'll also need to normalize the pixel values.

Finally, convert your image back to a NumPy array using the .numpy() method.

In [12]:
# TODO: Create the process_image function
def process_image(image_array):
    image_tensor = tf.convert_to_tensor(image_array, dtype=tf.float32)
    image_tensor = tf.image.resize(image_tensor, (size, size))
    image_tensor /= 255
    image_array = image_tensor.numpy()
    return image_array

To check your process_image function we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

The code below loads one of the above images using PIL and plots the original image alongside the image produced by your process_image function. If your process_image function works, the plotted image should be the correct size.

In [14]:
from PIL import Image
size  = 224
image_path = './test_images/hard-leaved_pocket_orchid.jpg'
im = Image.open(image_path)
test_image = np.asarray(im)

processed_test_image = process_image(test_image)

fig, (ax1, ax2) = plt.subplots(figsize=(10,10), ncols=2)
ax1.imshow(test_image)
ax1.set_title('Original Image')
ax2.imshow(processed_test_image)
ax2.set_title('Processed Image')
plt.tight_layout()
plt.show()

Once you can get images in the correct format, it's time to write the predict function for making inference with your model.

Inference

Remember, the predict function should take an image, a model, and then returns the top $K$ most likely class labels along with the probabilities. The function call should look like:

probs, classes = predict(image_path, model, top_k)

If top_k=5 the output of the predict function should be something like this:

probs, classes = predict(image_path, model, 5)
print(probs)
print(classes)
> [ 0.01558163  0.01541934  0.01452626  0.01443549  0.01407339]
> ['70', '3', '45', '62', '55']

Your predict function should use PIL to load the image from the given image_path. You can use the Image.open function to load the images. The Image.open() function returns an Image object. You can convert this Image object to a NumPy array by using the np.asarray() function.

Note: The image returned by the process_image function is a NumPy array with shape (224, 224, 3) but the model expects the input images to be of shape (1, 224, 224, 3). This extra dimension represents the batch size. We suggest you use the np.expand_dims() function to add the extra dimension.

In [15]:
# TODO: Create the predict function
def predict(image_path, model, top_k=5):
    image =  Image.open(image_path)
    image_array = np.asarray(image)
    image_array = process_image(image_array)
    image_array = np.expand_dims(image_array, axis=0)
    probs = model.predict(image_array)
    class_names_ls = list(class_names.values())
    df = pd.DataFrame({'probs':probs[0],
                      'classes':class_names_ls})
    df = df.sort_values('probs')
    top_values = df.tail(top_k)
    classes = top_values['classes']
    probs = top_values['probs']
    return probs, classes

Sanity Check

It's always good to check the predictions made by your model to make sure they are correct. To check your predictions we have provided 4 images in the ./test_images/ folder:

  • cautleya_spicata.jpg
  • hard-leaved_pocket_orchid.jpg
  • orange_dahlia.jpg
  • wild_pansy.jpg

In the cell below use matplotlib to plot the input image alongside the probabilities for the top 5 classes predicted by your model. Plot the probabilities as a bar graph. The plot should look like this:

You can convert from the class integer labels to actual flower names using class_names.

In [17]:
# TODO: Plot the input image along with the top 5 classes
root_path = './test_images/'
image_paths = ['cautleya_spicata.jpg',
              'hard-leaved_pocket_orchid.jpg',
              'orange_dahlia.jpg',
              'wild_pansy.jpg']


image = random.choice(image_paths)
image_path = root_path + image
flower = Image.open(image_path)
ps, classes = predict(image_path, reloaded_keras_model, top_k=5)

fig, (ax1, ax2) = plt.subplots(figsize=(6,9), ncols=2)
ax1.imshow(flower, cmap = plt.cm.binary)
ax1.axis('off')
ax1.set_title(classes.values[0])

ax2.barh(np.arange(5), ps)
ax2.set_aspect(0.1)
ax2.set_yticks(np.arange(5))
ax2.set_yticklabels(classes[::-1], size='small');
ax2.set_title('Class Probability')
ax2.set_xlim(0, 1.1)
plt.tight_layout();
1/1 [==============================] - 0s 50ms/step